package com.dferreira.axil.controller;

import javax.annotation.PostConstruct;
import javax.enterprise.inject.Model;
import javax.enterprise.inject.Produces;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

import com.dferreira.axil.data.RepositorioDeClientes;
import com.dferreira.axil.model.Cliente;
import com.dferreira.axil.service.CadastroDeCliente;

@Model
public class ClienteController {

    @Inject
    private FacesContext facesContext;

    @Inject
    private CadastroDeCliente cadastro;

    @Inject
    private RepositorioDeClientes repositorio;
    
    @Produces
    @Named
    private Cliente cliente;
    
    @PostConstruct
    public void inicializar() {
        cliente = new Cliente();
        FacesContext.getCurrentInstance().getExternalContext().getSession(true);
    }

    public String salvar() {
        try {
            cadastro.salvar(cliente);
            FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_INFO, "Cliente salvo.", null);
            facesContext.addMessage(null, m);
            inicializar();
            return "listaDeClientes";
        } catch (Exception e) {
            String errorMessage = getRootErrorMessage(e);
            FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMessage, "Erro ao realizar cadastro.");
            facesContext.addMessage(null, m);
            return null;
        }
    }
    
    public String salvarEAdicionar() {
    	salvar();
    	return "cliente";
    }
    
    public String editar(Long id) {
    	cliente = repositorio.findById(id);
    	return "cliente";
    }
    
    public void excluir(Long id) throws Exception {
    	Cliente cliente = new Cliente();
    	cliente.setId(id);
    	cadastro.excluir(cliente);
    }

    private String getRootErrorMessage(Exception e) {
        String errorMessage = "Registration failed. See server log for more information";
        if (e == null) {
            return errorMessage;
        }

        Throwable t = e;
        while (t != null) {
            errorMessage = t.getLocalizedMessage();
            t = t.getCause();
        }
        return errorMessage;
    }

}
